package com.xxh.message.controller;

import com.xxh.common.constant.MessageConstants;
import com.xxh.common.utils.Result;
import com.xxh.common.utils.WebUtils;
import com.xxh.dataaccess.dto.ContactMessageDto;
import com.xxh.dataaccess.dto.Contacts;
import com.xxh.dataaccess.dto.message.ReplyMessageDto;
import com.xxh.dataaccess.entity.UserMessage;
import com.xxh.dataaccess.service.ChatMessageService;
import com.xxh.dataaccess.service.UserMessageService;
import com.xxh.message.handler.MessageEventHandler;
import com.xxh.message.payload.BroadCastRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    ChatMessageService chatMessageService;

    @Autowired
    MessageEventHandler handler;


    @Autowired
    UserMessageService userMessageService;


    /**
     * @param uid 用户ID，测试的时候传的
     * @return 当前用户聊过天的联系人
     */
    @GetMapping("/getContacts")
    public Result getContractPeople(@RequestParam(value = "uid", required = false) Integer uid) {
        Integer id = Math.toIntExact(WebUtils.getUserId());
        List<Contacts> contacts = chatMessageService.getContacts(id);

        return Result.success().put("contacts", contacts);
    }


    /**
     * @param cid 联系人 ID
     * @return 获取和联系人的会话消息
     */
    @GetMapping("/getContactMessage")
    public Result getChatMessage(@RequestParam(value = "cid", required = true) Integer cid) {
        //当前用户ID
        Integer uid = Math.toIntExact(WebUtils.getUserId());
        List<ContactMessageDto> message = chatMessageService.pullContactMessage(uid, cid);
        return Result.success().put("message", message);
    }


    @PostMapping("/broadcast")
    public Result sendBroadCast(BroadCastRequest request) {
        handler.SendBroadCast(request);
        return Result.success();
    }

    //用户查询消息
    @GetMapping("/getMessage")
    public Result getMessage(@RequestParam(name = "type", required = true) String type) {

        Result result = Result.success();
        //当前用户
        Long id = WebUtils.getUserId();
        switch (type) {
            case MessageConstants.SYS_MSG:
                List<UserMessage> message = userMessageService.getSysMessageByUid(Math.toIntExact(id));
                result.put("message", message);
                break;
            case MessageConstants.LIKE_MSG:
                break;
            case MessageConstants.Reply_MSG:
                List<ReplyMessageDto> replyMessage = userMessageService.getUserReplyMessage(Math.toIntExact(id));
                result.put("message", replyMessage);
        }
        return result;
    }

}
